<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>设表先关方法</title>
    <style>
        * {
          margin: 0;
          padding: 0;
        }
        .box {
          position: absolute;
          top: 100px;
          left: 0;
          width: 100px;
          height: 100px;
          background-color: pink;
        }
      </style>
</head>
<body>
    <input type="button" value="开始" id="start">
    <input type="button" value="结束" id="end">
    <div class="box" id="box"></div>
    <script>
        // 获取元素
        var start = document.getElementById("start");
        var end = document.getElementById("end");
        var box = document.getElementById("box");
        // 信号量
        var nowLeft = 0;
        // 全局变量存储定时器
        var timer;
        // 设表先关
        start.onclick = function () {
          // 清除定时器
          clearInterval(timer);
          timer = setInterval(function () {
            // 信号量进行自加
            nowLeft += 10;
            // 将最新的 nowLeft 的值赋值给元素的 css 属性
            box.style.left = nowLeft + "px";
          },100);
        };
        // 清除定时器
        end.onclick = function () {
          clearInterval(timer);
        };
    </script>
</body>
</html>